<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option :label="obj.cate_name" :value="obj.id" v-for="obj in cateList" :key="obj.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="chooseFn">筛选</el-button>
            <el-button type="info" size="small" @click="resetFn">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="showPubDialog">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%" border stripe>
        <el-table-column prop="title" label="文章标题">
          <template v-slot="scope">
            <el-link type="primary" @click="showDetailFn(scope.row.id)">{{scope.row.title}}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="文章分类">
        </el-table-column>
        <el-table-column prop="pub_date" label="发布时间">
          <template v-slot="scope">
            {{$formatDate(scope.row.pub_date)}}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
                <el-button type="danger" size="mini" @click="removeFn(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>




      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChangeFn" @current-change="handleCurrentChangeFn"
        :current-page.sync="q.pagenum" :page-sizes="[2, 3, 5, 10]" :page-size.sync="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 对话框 -->
    <el-dialog title="发表文章" :visible.sync="pubDialogVisible" fullscreen :before-close="handleClose"
      @close="closeDialogFn">
      <!-- 发布文章的对话框 -->
      <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
            <el-option :label="obj.cate_name" :value="obj.id" v-for="obj in cateList" :key="obj.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 富文本编辑器 -->
        <el-form-item label="文章内容" prop="content">
          <quill-editor v-model="pubForm.content" @blur="changeEditorFn">
          </quill-editor>
        </el-form-item>

        <!-- 封面标签 -->
        <el-form-item label="文章封面" prop="cover_img">
          <!-- 用来显示封面的图片 -->
          <img src="../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input type="file" style="display: none;" accept="image/*" ref="iptFileRef" @change="onCoverChangeFn" />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="chooseImgFn">+ 选择封面</el-button>
        </el-form-item>
        <!-- 提交标签 -->

        <el-form-item>
          <el-button type="primary" @click="pubArticleFn('已发布')">发布</el-button>
          <el-button type="info" @click="pubArticleFn('草稿')">存为草稿</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

    <!-- 查看文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>

      <div class="info">
        <span>作者：{{artDetail.nickname || artDetail.username}}</span>
        <span>发布时间：{{$formatDate(artDetail.pub_date)}}</span>
        <span>所属分类：{{artDetail.cate_name}}</span>
        <span>状态{{artDetail.state}}：</span>
      </div>

      <!-- 分割线 -->
      <el-divider></el-divider>

      <!-- 文章的封面 -->
      <img :src="baseRURL+artDetail.cover_img" alt="" />

      <!-- 文章的详情 -->
      <div v-html="artDetail.content" class="detail-box"></div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getCateListAPI,
    pubNewArtAPI,
    getArtListAPI,
    getArtDetailAPI,
    deleteArtByIdAPI
  } from "@/api"
  import imgObj from "@/assets/images/cover.jpg"
  import {baseURL} from "@/utils/request.js"
  import {
    Form
  } from "element-ui"
  export default {
    name: 'ArtList',
    data() {
      return {
        //图片基地址
        baseRURL:baseURL,
        // 查询参数对象
        q: {
          pagenum: 1,
          pagesize: 2,
          cate_id: '',
          state: ''
        },
        pubDialogVisible: false,
        pubForm: {
          title: '',
          cate_id: '',
          content: "",
          cover_img: "",
          state: "" //文章状态：已发布或草稿
        },
        pubFormRules: { // 表单的验证规则对象
          title: [{
              required: true,
              message: '请输入文章标题',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 30,
              message: '文章标题的长度为1-30个字符',
              trigger: 'blur'
            }
          ],
          cate_id: [{
            required: true,
            message: '请选择文章分类',
            trigger: 'change'
          }],
          content: [{
            required: true,
            message: "请编写文章内容",
            trigger: 'change'
          }],
          cover_img: [{
            required: true,
            message: "请上传封面",
            trigger: 'change'
          }]
        },
        cateList: [], //文章分类列表
        artList: [], //文章列表
        total: 0, //文章总数 默认为0
        detailVisible:false ,//控制文章详细对话框
        artDetail:{}//文章详细
      }
    },
    created() {
      //获取文章分类
      this.getCateList()
      //获取文章数据
      this.getArtList()
    },
    methods: {
      //获取文章列表
      async getArtList() {
        const {
          data: res
        } = await getArtListAPI(this.q)
        //赋值
        this.artList = res.data
        this.total = res.total
      },
      //获取文章分类列表
      async getCateList() {
        const {
          data: res
        } = await getCateListAPI()
        this.cateList = res.data
      },
      showPubDialog() {
        this.pubDialogVisible = true
      },
      async handleClose(done) {
        const confirmResult = await this.$confirm("此操作将导致文章信息丢失, 是否继续?", '提示', {
          confirmButtonText: "确定",
          confirmButtonClass: "取消"
        }).catch(err => err)
        //阻止提交什么都不干
        if (confirmResult == 'cancel') return
        done() //放行
      },
      //触发提交图片的点击事件
      chooseImgFn() {
        this.$refs.iptFileRef.click() //触发文件input框的点击事件
      },
      //接受图片
      onCoverChangeFn(e) {
        const files = e.target.files //接受文件对象
        if (files.length == 0) {
          this.pubForm.cover_img = null
          //图片预览
          this.$refs.imgRef.setAttribute("src", imgObj)
        } else {
          this.pubForm.cover_img = files[0]
          //图片预览
          const url = URL.createObjectURL(files[0])
          //修改img标签属性
          this.$refs.imgRef.setAttribute("src", url)
        }
        this.$refs.pubFormRef.validateField("cover_img")
      },
      //提交文章
      pubArticleFn(state) {
        this.pubForm.state = state

        //js兜底检验
        this.$refs.pubFormRef.validate(async valid => {
          if (valid) {
            const fd = new FormData()
            fd.append("title", this.pubForm.title)
            fd.append("cate_id", this.pubForm.cate_id)
            fd.append("content", this.pubForm.content)
            fd.append("cover_img", this.pubForm.cover_img)
            fd.append("state", this.pubForm.state)
            const {
              data: res
            } = await pubNewArtAPI(fd)
            if (res.code !== 0) return this.$message.error("文章发送失败")
            this.$message.success("文章发送成功")
            this.pubDialogVisible = false
            //重新请求数据
            this.getArtList()
          } else {
            return false
          }
        })
      },
      //自定义富文本校验
      changeEditorFn() {
        //只校验content这个规则
        this.$refs.pubFormRef.validateField("content")
      },
      //关闭发布页时，清空页面
      closeDialogFn() {
        this.$refs.pubFormRef.resetFields()
        //清空图片
        this.$refs.imgRef.setAttribute("src", imgObj)
      },
      //每页大小发生改变时触发的回调
      handleSizeChangeFn(sizes) {
        //sizes代表已经变化的页码
        //因为page-size有sync修饰，实现了双向绑定则可以不用修改q中的属性
        this.q.pagesize = sizes //保险起见
        //每页条数发生变化有可能导致页的数量改变，从而触发页数改变的函数
        //这种情况下会产生bug
        //即请求大于页码的页号（原因:前端向后台发送两次请求）
        //解决办法:每次每页的条数发生变化时，就把页码(pagenum)置为1
        this.q.pagenum = 1
        this.getArtList()
      },
      //当前页改变时发生的回调
      handleCurrentChangeFn(pages) {
        this.q.pagenum = pages
        this.getArtList()
      },
      //文章筛选功能
      chooseFn() {
        this.q.pagenum = 1
        this.q.pagesize = 2
        this.getArtList()
      },
      //重置表单
      resetFn() {
        this.q.cate_id = ''
        this.q.pagenum = 1
        this.q.pagesize = 2
        this.q.state = ''

        this.getArtList()
      },
      //展示文章详细
      async showDetailFn(id) {
        const {data:res} = await getArtDetailAPI(id)
        this.artDetail=res.data
        this.detailVisible=true
      },
      //删除标签
      async removeFn(id){
          const confirmResult=await this.$confirm("此操作将永久删除该文章,是否继续",'提示',{
            confirmButtonText:"确认",//确认按钮
            cancelButtonText:"取消",//取消按钮
            type:'warning'
          }).catch(error=>error)
          //取消了删除
          if(confirmResult==="cancel") return this.$message("取消删除")
          //确认删除
          //判断当前数据是否为最后一页的最后一行
          if(this.artList.length===1){
            //判断当前页码是否大于1
            if(this.q.pagenum>1){
              this.q.pagenum--
            }
          }
          const{data:res} =await deleteArtByIdAPI(id)
          if(res.code!==0) return this.$message.error("删除失败")
          this.$message.success("删除成功!")
          this.getArtList()
      }
    }
  }
</script>

<style lang="less" scoped>
  .search-box {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .btn-pub {
      margin-top: 5px;
    }
  }

  ::v-deep .ql-editor {
    min-height: 300px;
  }

  // 设置图片封面的宽高
  .cover-img {
    width: 400px;
    height: 280px;
    object-fit: cover;
  }

  .title {
    font-size: 24px;
    text-align: center;
    font-weight: normal;
    color: #000;
    margin: 0 0 10px 0;
  }

  .info {
    font-size: 12px;
    span {
      margin-right: 20px;
    }
  }

  // 修改 dialog 内部元素的样式，需要添加样式穿透
  ::v-deep .detail-box {
    img {
      width: 500px;
    }
  }
</style>
